import http from 'node:http'
import OpenAI from 'openai';
import os from 'node:os';
import fs from 'node:fs';

const openai = new OpenAI({
  apiKey: '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', // defaults to process.env["OPENAI_API_KEY"]
});
const getData = () => {

  return new Promise((resolve, reject) => {
    const rs = fs.createReadStream(path.join(__dirname, '/Users/lz/Downloads/node-v18.17.1.pkg'), {
      fd: null,
      flags: 'r',
      mode: 0o666,
      start: 0,
      encoding: null,
      autoClose: true,
      highWaterMark: 64 * 1024,
    });
    rs.on('data', (res) => {
      resolve(res)
    });
  })
}
async function hanldle(req, res) {
  res.setHeader('Content-Type', 'text/event-stream');
  res.setHeader('Connection', 'keep-alive');
  res.setHeader('Cache-Control', 'no-cache');

  // const rs = fs.createReadStream('/Users/lz/Downloads/node-v18.17.1.pkg', {
  //   fd: null,
  //   flags: 'r',
  //   mode: 0o666,
  //   start: 0,
  //   encoding: null,
  //   autoClose: true,
  // });
  // // rs.on('error', (res) => {
  // //   console.log(res)
  // // });
  // // res.write(rs.read)
  // rs.on('data', (data) => {
  //   res.write(`data: ${data}\n\n`); // 写入数据(推送数据)
  // });
  // rs.on('end', () => {
  //   console.log("end")
  //   res.end("data: [DONE]")
  // })

  const stream = await openai.completions.create({
    messages: [{ role: 'user', content: "webpack 是什么，写一个demo" }],
    model: 'gpt-3.5-turbo',
    stream: true,
  }, { stream: true });

  res.end(`data:${stream.choices}`);
}
const server = http.createServer((req, res) => {

  if (req.url !== "/favicon.ico" && req.url === '/chatgpt') {
    console.log("====1")

    hanldle(req, res)
    // console.log("====2")
    // res.end("data: start")
    // let body = '';
    // req.on('data', chunk => {
    //   body += chunk.toString(); // 将接收到的数据拼接起来  
    // });
    // req.on('end', async () => {



    // });

  } else if (req.url === '/html' && req.method === 'GET') {
    const responseText = fs.readFileSync('./index.html', 'utf8')
    res.end(responseText)
  } else {
    res.end("Hello world !")
  }


});
server.listen(3000, () => {
  let networkInterfaces = os.networkInterfaces();
  let addresses = [];

  for (let k in networkInterfaces) {
    for (let k2 in networkInterfaces[k]) {
      let address = networkInterfaces[k][k2];
      if (address.family === 'IPv4' && !address.internal) {
        addresses.push(address.address);
      }
    }
  }
  console.log("server start:", `http://${addresses?.[0]}:3000`)
});


